package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: 成金乘
 * @date: 2023/5/14 17:26
 * @description:
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求的编码
        req.setCharacterEncoding("utf8");
        //响应的编码
        resp.setContentType("text/html;charset=utf8");
        //判读那用户名和密码是否为空
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(null == username || username.equals("") || null == password || password.equals("")){
            //登陆失败
            String html = "<h3>登陆失败,用户名或密码错误<h3>";
            resp.getWriter().write(html);
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectByUsername(username);
        if (user == null){
            //用户不存在
            String html = "<h3>登陆失败,用户名或密码错误<h3>";
            resp.getWriter().write(html);
            return;
        }
        if(!password.equals(user.getPassword())){
            //密码错误
            String html = "<h3>登陆失败,用户名或密码错误<h3>";
            resp.getWriter().write(html);
            return;
        }
        //验证通过
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");

        HttpSession session = req.getSession(false);
        if(session == null){
            //未登录
            User user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        User user = (User)session.getAttribute("user");
        if(user == null){
            user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        //存在
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
